<template>
  <div>
    <div>
      <!-- 搜索区 -->
      <Search
        v-model="queryModel.query"
        :loading="queryLoading"
        @search="
          queryModel.pagenum = 1;
          getUsersList();
        "
        @click="
          model = {};
          $refs.d.show();
        "
      >
        添加用户
      </Search>
      <!-- 表格 -->
      <MyTable
        :loading="tableLoading"
        :data="list"
        :cols="cols"
        v-model="queryModel"
        @change="getUsersList"
        :total="total"
      >
        <template v-slot:state="{ row }">
          <el-switch
            @change="switchState(row)"
            v-model="row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
        <template v-slot:action="{ row }">
          <el-button
            size="mini"
            type="primary"
            @click="
              model = { ...row };
              $refs.d.show();
            "
            ><i class="el-icon-edit"></i
          ></el-button>
          <el-button size="mini" type="danger" @click="delteUser(row)"
            ><i class="el-icon-delete"></i
          ></el-button>
          <el-button
            size="mini"
            type="warning"
            @click="
              model = { ...row };
              getRoleList();
            "
            ><i class="el-icon-s-tools"></i
          ></el-button>
        </template>
      </MyTable>
      <!-- 添加修改 -->
      <DF
        :title="title + '用户'"
        ref="d"
        v-model="model"
        :opts="opts"
        @confirm="confirm"
      />
      <!-- 分配角色 -->
      <MyDialog title="分配角色" ref="ad" @confirm="changeRole">
        <p>当前的用户：{{ model.username }}</p>
        <p>当前的角色：{{ model.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="model.rid">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </MyDialog>
    </div>
  </div>
</template>
<script>
import { getUsers, changeState, addUser, updataUser, delUser } from "api/user";
import { getRoles, updateRole } from "api/rights";
import { pageMixins } from "@/mixins/baseMixins";

export default {
  mixins: [pageMixins],
  name: "users",
  data() {
    return {
      queryLoading: false,
      /**
       * 添加修改模型
       */
      model: {},
      /**
       * 角色列表
       */
      roles: [],
      /**
       * 表格loading
       */
      tableLoading: false,
      /**
       * 列
       */
      cols: [
        {
          title: "#",
          type: "index",
        },
        {
          title: "姓名",
          name: "username",
        },
        {
          title: "邮箱",
          name: "email",
        },
        {
          title: "电话",
          name: "mobile",
        },
        {
          title: "角色",
          name: "role_name",
        },
        {
          title: "状态",
          slot: "state",
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 270,
        },
      ],
    };
  },
  methods: {
    /**
     * 修改角色
     */
    async changeRole() {
      const ad = this.$refs.ad;
      try {
        ad.start();
        await updateRole(this.model.id, this.model.rid);
        this.$m.success("角色修改成功");
        ad.hide();
        this.getUsersList();
      } catch (error) {
        console.log(error);
      }
      ad.stop();
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      try {
        this.tableLoading = true;
        this.roles = await getRoles();
        console.log(this.roles);
        const rid =
          this.roles.find((c) => c.roleName === this.model.role_name)?.id ??
          this.roles[0].id;
        this.$set(this.model, "rid", rid);
        this.$refs.ad.show();
      } catch (error) {
        console.log(error);
      }
      this.tableLoading = false;
    },
    /**
     * 删除用户
     */
    async delteUser({ id, username }) {
      let res;
      try {
        res = await this.$myConfirm(`您确定要删除【${username}】吗？`);
        await delUser(id);
        this.$m.success("删除成功");
        this.getUsersList();
      } catch (error) {}
      res && res();
    },
    /**
     * 提交添加修改
     */
    async confirm() {
      const d = this.$refs.d;
      try {
        // await this.$refs.form.validate();
        d.start();
        await (this.model.id ? updataUser : addUser)(this.model);
        d.hide();
        this.$m.success(this.title + "成功");
        this.getUsersList();
      } catch (error) {}
      d.stop();
    },
    async getUsersList() {
      try {
        this.queryLoaing = true;
        const { total, users } = await getUsers(this.queryModel);
        this.total = total;
        this.list = users;
      } catch (error) {}
      this.queryLoaing = false;
    },
    async switchState({ id, mg_state }) {
      try {
        await changeState(id, mg_state);
        this.$m.success("状态更新成功");
        this.getUsersList();
      } catch (error) {}
    },
  },
  computed: {
    /***
     * 表单配置项
     */
    opts() {
      return {
        username: {
          title: "用户名",
          required: true,
          tag: "input",
          type: "text",
          max: 10,
          dis: !!this.model.id,
          ph: "请输入用户名",
          rules: [{ min: 5, max: 10 }],
        },
        ...(this.model.id
          ? {}
          : {
              password: {
                title: "密码",
                required: true,
                tag: "input",
                type: "password",
                max: 15,
                ph: "请输入密码",
              },
            }),
        email: {
          title: "邮箱",
          required: true,
          max: 30,
          rules: [{ type: "email", message: "邮箱格式不正确" }],
        },
        moblie: {
          title: "手机",
          required: true,
          max: 11,
          rules: [{ pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" }],
        },
      };
    },
    /***
     * 标题
     */
    title() {
      return this.model.id ? "修改" : "添加";
    },
  },
  created() {
    this.getUsersList();
  },
};
</script>
<style scoped lang="scss">
.search-input {
  width: 400px;
  margin-right: 20px;
}
</style>